# -*- coding: utf-8 -*-
import logging

from datetime import datetime, timedelta
from odoo import fields, models, api

from . import utils

_logger = logging.getLogger(__name__)


class TravelProduct(models.Model):
    """旅游产品，产品类型是服务"""
    _name = "tour.travel.product"
    _description = u'旅游线路'
    _inherit = 'product.product'
    _table = 'product_product'

    days_count = fields.Float(string=u'行程天数')
    display_pic = fields.Html(string=u'封面图片预览', compute='_compute_display_pic')
    cover_pic = fields.Many2one('ir.attachment', string=u'封面图片')

    @api.depends('cover_pic')
    @api.onchange('cover_pic')
    def _compute_display_pic(self):
        for each_record in self:
            if each_record.cover_pic:
                each_record.display_pic = """
                <img src="{pic}" style="max-width:100px;">
                """.format(pic=each_record.cover_pic.static_link())
            else:
                each_record.display_pic = False


class OwnerProduct(models.Model):
    """车主提供服务的产品"""
    _name = 'tour.owner.product'
    _description = u'车主产品'

    name = fields.Char(string=u'名称', compute='_compute_name')
    owner_id = fields.Many2one('tour.owner', string=u"车主", requited=True)
    product_id = fields.Many2one('tour.travel.product', string=u'旅游线路')  # 净车价不需要选择线路
    city_id = fields.Many2one('tour.city', string=u'出发城市', requited=True)
    price = fields.Float(string=u'价格')  # 通用价格，每日单价
    charge_refund = fields.Boolean(string=u'是否退劳务费', default=False)
    active = fields.Boolean(string=u'有效', default=True)

    @api.multi
    def _compute_name(self):
        for p in self:
            p.name = p.owner_id.name + '-' + p.product_id.name

    def search_owner_line(self, start_date, end_date, people_count, model_id, int_product_id, buy_year, int_city_id):
        """根据开始日期，结束日期，核定载人数，车辆类型，线路名称、车辆年限，出发城市查询符合条件的车辆线路
        start_date：开始日期，必传
        end_date：结束日期，必传
        people_count: 核定载人数 非必填
        model_id：车型 非必填
        int_product_id：线路 非必填
        buy_year：购车年份 非必填
        int_city_id：出发城市 非必填
        """
        tour_date = datetime.strptime(start_date, "%Y-%m-%d")
        ok_owner_ids = []  # 最终符合条件的车主

        # 根据车辆核载人数查询合适的车主
        vehicle_domain = []
        if people_count > 0:
            vehicle_domain += [('people_count', '=', people_count)]
        if model_id > 0:
            vehicle_domain += [('model_id', '=', model_id)]
        if buy_year > 0:
            vehicle_domain += [('buy_year', '=', buy_year)]
        vehicle_ids = self.env['tour.vehicle'].search(vehicle_domain)
        int_owner_ids = [x.owner_id.id for x in vehicle_ids]

        # 根据出发日期和行程天数计算行程所占用的日期
        use_dates = [start_date]
        year1 = int(start_date.split('-')[0])
        month1 = int(start_date.split('-')[1])
        day1 = int(start_date.split('-')[2])

        year2 = int(end_date.split('-')[0])
        month2 = int(end_date.split('-')[1])
        day2 = int(end_date.split('-')[2])
        # 租车天数，包括开始日期和结束日期
        order_days = utils.daysBetweenDates(year1, month1, day1, year2, month2, day2)
        i = 1
        while i <= order_days:
            use_dates.append(fields.Date.to_string(fields.Date.from_string(start_date) + timedelta(days=i)))
            i += 1

        # 根据车主忙碌日期过滤出有空的车主
        int_busy_owner_ids = []
        for date in use_dates:
            busy_drivers = self.env['tour.owner.busy'].search([('busy_date', '=', date), ('active', '=', True)])
            for busy_driver in busy_drivers:
                if busy_driver.owner_id.id not in int_busy_owner_ids:
                    int_busy_owner_ids.append(busy_driver.owner_id.id)

        # 根据订单明细过滤已被订购的车辆线路
        order_owner_ids = []
        for date in use_dates:
            order_domain = [('state', 'not in', ['draft', 'cancel']), ('start_date', '<=', date),
                            ('end_date', '>=', date)]
            orders = self.env['tour.sale.order'].search(order_domain)
            for order in orders:
                if order.owner_id.id not in order_owner_ids:
                    if int_product_id > 0:
                        product_flag = False
                        for line in order.order_line:
                            if int_product_id == line.product_id.id:
                                product_flag = True
                                break
                        if product_flag:
                            order_owner_ids.append(order.owner_id.id)
                    else:
                        order_owner_ids.append(order.owner_id.id)

        for id in int_owner_ids:
            if id not in int_busy_owner_ids and id not in order_owner_ids:
                ok_owner_ids.append(id)

        # 最终过滤车辆线路
        result = []
        owner_product_domain = [('owner_id', 'in', ok_owner_ids), ('active', '=', True)]
        if int_product_id > 0:
            owner_product_domain += [('product_id', '=', int_product_id)]
        if int_city_id > 0:
            owner_product_domain += [('city_id', '=', int_city_id)]
        owner_product_ids = self.search(owner_product_domain)

        for owner_product in owner_product_ids:
            price = owner_product.price

            # 计算订单价格。如果车主设置了特殊价格，则取特殊价格
            order_line = []
            lst_special_price = self.env['tour.product.price'].search_read(
                [('owner_product_id', '=', owner_product.id),
                 ('start_date', '<=', start_date),
                 ('end_date', '>=', start_date),
                 ('active', '=', True)], ['special_price'], limit=1)
            if lst_special_price:
                price = lst_special_price[0]['special_price']
            # 旅游第一天
            order_line.append((0, 0, {'product_id': owner_product.product_id.id, 'name': owner_product.product_id.name,
                                      'owner_product_id': owner_product.id, 'price': price, 'travel_date': start_date}))

            index = 1
            while index < order_days:
                next_date = datetime.strftime(tour_date + timedelta(days=index), "%Y-%m-%d")
                lst_special_price = self.env['tour.product.price'].search_read(
                    [('owner_product_id', '=', owner_product.id),
                     ('start_date', '<=', next_date),
                     ('end_date', '>=', next_date),
                     ('active', '=', True)], ['special_price'], limit=1)
                if lst_special_price:
                    price = lst_special_price[0]['special_price']
                # 旅游其他天
                order_line.append(
                    (0, 0, {'product_id': owner_product.product_id.id, 'name': owner_product.product_id.name,
                            'owner_product_id': owner_product.id, 'price': price,
                            'travel_date': next_date}))
                index += 1

            # 计算订单总额
            order_amount = 0
            for x in order_line:
                order_amount += x[2]['price']
            vals = {'id': owner_product.id, 'name': owner_product.name, 'price': order_amount}
            result.append(vals)

        return result


class ProductPrice(models.Model):
    """车主产品特殊价格表，车主可以针对某一段特殊日期设置涨价或降价"""
    _name = "tour.product.price"
    _description = u'车主产品特殊价格表'

    owner_product_id = fields.Many2one('tour.owner.product', string=u"车辆线路")
    special_price = fields.Float(string=u'价格', requited=True)  # 特殊价格
    start_date = fields.Date(string=u'开始日期', requited=True)
    end_date = fields.Date(string=u'结束日期', requited=True)
    active = fields.Boolean(string=u'状态', default=True)
